package com.wf.classRoomTest.run;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author fengqq
 * @Description TODO
 * @Date 2024/6/14  10:04
 */
public class Print {
    //当前线程要打印的字母
    static  String letter = "A";

    public static void main(String[] args) {
        //对象锁 this
        Lock lock = new ReentrantLock();
        //负责线程A的等待和唤醒
        Condition conditionA = lock.newCondition();
        //负责线程B的等待和唤醒
        Condition conditionB = lock.newCondition();
        //负责线程C的等待和唤醒
        Condition conditionC = lock.newCondition();



        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    lock.lock();
                    if (!letter.equals("B")) {
                        conditionB.await();
                    }
                    System.out.print("B");
                    letter = "C";
                    conditionC.signal();
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    lock.unlock();
                }
            }
        }).start();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {

            try {
                lock.lock();
                if (!letter.equals("C")) {
                    conditionC.await();
                }
                System.out.println("C");
                letter = "A";
                conditionA.signal();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
            }

    }).start();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    lock.lock();
                    if (!letter.equals("A")) {
                        //如果要打印的字母不是A 则当前线程A处于等待状态
                        conditionA.await();// 会释放对象锁
                    }
                    System.out.print("A");
                    letter = "B";
                    //通知 线程B来操作
                    conditionB.signal();
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    lock.unlock();
                }
            }

        }).start();


}


    }



